package com.hero.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.json.JSONUtil;
import com.hero.domain.CourseIndex;
import com.hero.domain.CoursePublish;
import com.hero.feignClients.SearchClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author yunfei
 * @date 2022年12月31日 16:21
 */
@Component
@Slf4j
public class CoursePublishESListener {


    /**
     * 写消费者者的时候要始终想着 幂等性问题
     */

    @Autowired
    private SearchClient searchClient;

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(name = "coursePublish", type = "fanout"),
            value = @Queue(name = "esMQ")
    ))
    public void coursePublishRedisConsumer(String publishStr) {
        CoursePublish coursePublish = JSONUtil.toBean(publishStr, CoursePublish.class);
        System.out.println("coursePublish = " + coursePublish);
        // 把课程基本信息保存到ES中
        // 发起Feign调用Search微服务
        // 1.  直接在这写ES的代码(推荐使用这个)
        // 2.  通过Feign调用search模块实现新增

        // 发起远程调用
        CourseIndex coruseIndex = new CourseIndex();
        BeanUtil.copyProperties(coursePublish, coruseIndex);
        // insert 非幂等性操作
        // 先从ES中查询一条数据
        CourseIndex course = searchClient.getCourseById(coursePublish.getId());

        if (ObjUtil.isNotNull(course)) {
            // 如果ES中有数据先进行删除
            Boolean delCourse = searchClient.delCourseById(coursePublish.getId());
            if (!delCourse) log.error("ES消费者添加数据已经存在,删除失败: {}", coursePublish.getId());
            return;
        }

        // 同一条数据往ES中添加多次会出现多条数据吗
        Boolean add = searchClient.add(coruseIndex);
        if (!add) log.error("ES消费者添加数据失败: {}", coursePublish.getId());
    }

}